// utils/request.ts

interface RequestConfig {
  url: string;
  method?:
    | 'GET'
    | 'POST'
    | 'PUT'
    | 'DELETE'
    | 'OPTIONS'
    | 'HEAD'
    | 'TRACE'
    | 'CONNECT';
  data?: any;
  header?: Record<string, string>;
  timeout?: number;
  baseURL?: string;
}

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

const DEFAULT_CONFIG: Partial<RequestConfig> = {
  baseURL: 'http://120.26.105.183:8081', // 默认请求地址
  timeout: 10000, // 默认超时时间
  header: {
    'Content-Type': 'application/json',
    Accept: 'application/json',
  },
};

/**
 * 封装 uni.request 请求
 * @param options 请求配置
 * @returns Promise<ApiResponse>
 */
const request = async <T = any>(
  options: RequestConfig
): Promise<ApiResponse<T>> => {
  const config: RequestConfig = {
    ...DEFAULT_CONFIG,
    ...options,
    header: {
      ...DEFAULT_CONFIG.header,
      ...options.header,
    },
  };

  // 拼接完整 URL
  if (!config.url.startsWith('http')) {
    config.url = config.baseURL + config.url;
  }

  // 请求拦截器：添加 token 等公共 header
  const token = uni.getStorageSync('access_token');
  // const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJ4Y3g6MTk2Njc1MjQwMjA4NjA4MDUxMyIsInJuU3RyIjoiVDY5UkJiWWhwakNEYldGVkhCRmp0cENDWmIzN3NObDkiLCJjbGllbnRpZCI6ImJlNzA1MmE3ZTRmODAyYzIwZGYxMGE4ZDEzMWFkYjEyIiwidGVuYW50SWQiOiIwMDAwMDAiLCJ1c2VySWQiOjE5NjY3NTI0MDIwODYwODA1MTMsInVzZXJOYW1lIjoiMTMxMTExMTExMTEifQ.YPfUDdPbi74BMFgkj8v7iGhcHiahaFzOGXayTNUaxJE'
  if (token) {
    config.header!.Authorization = `Bearer ${token}`;
    config.header!.Clientid = `be7052a7e4f802c20df10a8d131adb12`;
  }

  try {
    const res = await new Promise<UniApp.RequestSuccessCallbackResult>(
      (resolve, reject) => {
        const requestOptions: UniApp.RequestOptions = {
          url: config.url,
          method: config.method as any,
          data: config.data,
          header: config.header,
          timeout: config.timeout,
          success: (res) => resolve(res),
          fail: (err) => reject(err),
        };
        uni.request(requestOptions);
      }
    );

    // 响应拦截器：处理成功响应
    if (res.statusCode === 200) {
      const responseData = res.data as ApiResponse<T>;

      if (responseData.code === 200) {
        return responseData;
      } else if (responseData.code === 401) {
        // 401 未授权，清空 token 并跳转到登录页
        uni.removeStorageSync('access_token');
        uni.removeStorageSync('userInfo');
        uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/user/login',
          });
        }, 1500);
        throw new Error('登录已过期');
      } else {
        uni.showToast({ title: responseData.msg || '请求失败', icon: 'none' });
        throw new Error(responseData.msg || '请求失败');
      }
    } else {
      uni.showToast({ title: '网络异常', icon: 'none' });
      throw new Error('网络异常');
    }
  } catch (error: any) {
    // 避免重复显示错误提示，只在网络错误时显示
    if (!error.message || error.message === '网络异常') {
      uni.showToast({ title: error.message || '请求出错', icon: 'none' });
    }
    throw error;
  }
};

export default request;
export type { RequestConfig, ApiResponse };
